package com.icoolkj.ms.pay.config;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.Data;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.FileInputStream;
import java.security.PrivateKey;

@Data
@Configuration
public class PayConfig {

    @Data
    @Configuration
    @ConfigurationProperties(prefix = "wx.pay")
    public static class WechatPayConfig {
        private String appId;
        private String mchId;
        private String apiV3Key;
        private String privateKeyPath;
        private String privateCertPath;
        private String notifyUrl;
    }

    @Data
    @Configuration
    @ConfigurationProperties(prefix = "alipay")
    public static class AlipayConfig {
        private String appId;
        private String privateKey;
        private String publicKey;
        private String notifyUrl;
        private String returnUrl;
        private String gatewayUrl;
    }

    @Bean
    public CloseableHttpClient wechatPayClient(WechatPayConfig config) throws Exception {
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
                new FileInputStream(config.getPrivateKeyPath()));

        WechatPay2Credentials credentials = new WechatPay2Credentials(
                config.getMchId(),
                new PrivateKeySigner(config.getMchId(), merchantPrivateKey));

        return WechatPayHttpClientBuilder.create()
                .withMerchant(config.getMchId(), config.getAppId(), merchantPrivateKey)
                .withValidator(response -> true) // 暂时不验证应答签名
                .build();
    }

    @Bean
    public AlipayClient alipayClient(AlipayConfig config) {
        return new DefaultAlipayClient(
                config.getGatewayUrl(),
                config.getAppId(),
                config.getPrivateKey(),
                "json",
                "UTF-8",
                config.getPublicKey(),
                "RSA2"
        );
    }
} 